package com.chachazhan.logback.kestrel.formatter;

import ch.qos.logback.classic.spi.ILoggingEvent;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * Formatter implementation that json returns the logback message.
 *
 * @author mingqi.zhou
 */
public class JsonFormatter implements Formatter {

    private static Logger logger = LoggerFactory.getLogger(JsonFormatter.class);

    public String format(ILoggingEvent event) {

        Map<String, String> info = new HashMap<String, String>();
        info.put("level", event.getLevel().levelStr);
        info.put("logger", event.getLoggerName());
        info.put("timestamp", String.valueOf(event.getTimeStamp()));
        info.put("message", event.getMessage());

        Object[] args = event.getArgumentArray();
        try {
            if (args != null && args.length > 1) {
                int index = args.length;
                for (int i = 0; i < index - 1; i += 2) {
                    info.put(String.valueOf(args[i]), String.valueOf(args[i + 1]));
                }
            }
        } catch (Exception e) {
            logger.error("arg array parse error! args=" + args);
        }
        return JSON.toJSONString(info);
    }
}
